<?php

require './vendor/autoload.php';

class phpOfficeChajian extends Chajian
{
    /**
     * 导出word(最终结果word转pdf)
     * @param array $data 必填 一维数组
     * @param string $path 必填 模板文件路径
     * @param array $dataRow 选填 excel数据 二维数组
     * @param string $filename 选填 文件名称
     * @return bool
     */
    function downloadWord($data = array(), $path = '', $dataRow = array(), $filename = '')
    {

        if (file_exists($path)) return false;
        $path = './officeTemplate/' . $path;
        $tmp = new \PhpOffice\PhpWord\TemplateProcessor($path);//打开模板
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                if(empty($value)) {
                    $tmp->setValue($key, '');
                }else{
                    $tmp->setValue($key, $value);//替换变量name
                }
            }
        }

        if (!empty($dataRow)) {
            //rowNumber table 第一个模板变量
            $tmp->cloneRowAndSetValues('rowNumber', $dataRow);
        }

        ob_end_clean();
        ob_start();

        $time = md5(time());
        if (empty($filename)) {
            $pdfName = $time . ".pdf";
        }

        $pathdir = UPDIR . '/' . 'cache' . '/' . date('Y-m') . '/';
        @mkdir($pathdir, 0777, true);
        $wordPath = $pathdir . $time . ".docx";
        $tmp->saveAs($wordPath);
        $pdfPath = UPDIR . '/' . 'document' . '/' . date('Y-m') . '/';
        $path = $this->wordToPdf($wordPath, $pdfPath, $pdfName);
        m('documents')->download($pdfPath, $pdfName);
        unlink($wordPath);
    }

    /**
     * 导出excel
     * @param array $data table数据 二维数组
     * @param string $path 模版文件路径
     * @param array $dataTmp 模板数据 一维数组 array('C3' => '名称'， 'F3' => '地址');
     * param array $totalColumn 统计 一维数组 array('first' => 'B', 'second' => 'E')  //first 开始名称  second 结束名称
     * @param string $filename 文件名称
     * @return bool
     */
    function downloadExcel($data = array(), $path = '', $dataTmp = array(), $totalColumn = array(), $filename = '')
    {
        if (empty($data) || empty($path)) return false;
        $path = './officeTemplate/' . $path;
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
        $worksheet = $spreadsheet->getActiveSheet();

        //写入模板数据
        if (!empty($dataTmp)) {
            foreach ($dataTmp as $key => $value) {
                $worksheet->setCellValue($key, $value);
            }
        }

        $worksheet->getStyle ('B')->getNumberFormat()->setFormatCode ("0.00");
        $worksheet->getStyle ('C')->getNumberFormat()->setFormatCode ("0.00");
        $worksheet->getStyle ('D')->getNumberFormat()->setFormatCode ("0.00");
        $worksheet->getStyle ('E')->getNumberFormat()->setFormatCode ("0.00");
        $worksheet->getStyle ('F')->getNumberFormat()->setFormatCode ("0.00");

        $this->commonExcel($worksheet, $data, $totalColumn);

        // 结束进行导出
        ob_end_clean();
        ob_start();
        if (empty($filename)) {
            $filename = md5(time()) . ".xlsx";
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $filename);
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
    }

    /**
     * Notes: 根据分类生成Sheet
     * @Auther: lv
     * @Email: 578530370@qq.com
     * @Date: 2020/4/21 17:00
     * @param $data
     * @param string $path
     * @return bool
     */
    function downloadExcels($data, $path = '', $dataTmp = array())
    {
        if (empty($data) || empty($path)) return false;
        $path = './officeTemplate/' . $path;
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
        foreach ($data as $ke => $va) {
            if (empty($va['type'])) continue;
            $clonedWorksheet[$ke] = clone $spreadsheet->getSheetByName('Sheet1');
            $clonedWorksheet[$ke]->setTitle($va['type']);
            $spreadsheet->addSheet($clonedWorksheet[$ke]);

            $data1 = $va['data'];
            $worksheet = $clonedWorksheet[$ke];

            //写入模板数据
            if (!empty($dataTmp)) {
                foreach ($dataTmp as $key => $value) {
                    if($key == 'A1'&& !empty($va['type'])) {
                        $value .= '—'.$va['type'];
                    }
                    $worksheet->setCellValue($key, $value);
                }
            }

            $worksheet->getStyle ('F')->getNumberFormat()->setFormatCode ("0.00");

            //计算excel行与列
            $rows = 1;
            foreach ($worksheet->getRowIterator(2) as $row) {
                $rows += 1;
            }
            //设置表格样式
            $styleArray = [
                //设置居中方式
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, //水平居中
                    'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, //垂直居中
                ],
                //设置边框
                'borders' => [
                    'outline' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\style\Border::BORDER_THIN, //细边
                        'color' => ['argb' => '00000000'], //黑色
                    ],
                ],
            ];

            $ch = 65;
            $num = $rows;

            $numRow = 1;
            $totalPrice = 0;
            $totalNum = count($data1);
            $rowss = '';

            $number = 0; //序号默认值
            for ($va = 0; $va < $totalNum; $va++) {
                //设置序号
                $number += 1;
                $data1[$va]['id'] = $number;

                $num += 1;
                //设置行高
//                $worksheet->getRowDimension($num)->setRowHeight(25);
                $i = 0;

                $si = $va + 1;
                if ($si >= $totalNum) $si = $va - 1;

                //公司名称相同+1
                if ($data1[$va]['companyname'] == $data1[$si]['companyname']) {
                    $numRow += 1;
                }

                //判断mergepeojectids是否有值
                if (!empty($data1[$va]['mergepeojectids']) && $data1[$va]['name'] == $data1[$si]['name']) $rowss .= $num . ',';
                unset($data1[$va]['mergepeojectids']);
                $totalPrice += $data1[$va]['budget'];

                //写入列表数据
                foreach ($data1[$va] as $k => $v) {
                    $str = chr($ch + $i) . ($num);
                    $worksheet->getStyle($str)->applyFromArray($styleArray);
                    $worksheet->getStyle($str)->getFont()->setName('Arial')->setSize(11);
                    $worksheet->getStyle($str)->getAlignment()->setWrapText(true);
                    $worksheet->getCell($str)->setValue($v);
                    $i += 1;
                }
                //设置合并单元格
                if (($data1[$va]['name'] != $data1[$si]['name'] && !empty($rowss)) || (($va + 1 == $totalNum)  && $data1[$va]['name'] == $data1[$si]['name'] && !empty($rowss))) {
                    $rowss = trim($rowss, ',');
                    $column = explode(',', $rowss);
                    $column1 = $column[0];
                    $worksheet->mergeCells("C$column1:C$num");
                    $worksheet->mergeCells("J$column1:J$num");
                    $worksheet->mergeCells("K$column1:K$num");
                    $worksheet->mergeCells("L$column1:L$num");
                    $worksheet->mergeCells("M$column1:M$num");
                }

                //excel写入小计
                if ($data1[$va]['companyname'] != $data1[$si]['companyname'] && $numRow > 1) {
                    $num = $num+1;
                    $value = array(
                        'id' => '小计',
                        'companyname' => '',
                        'name' => '',
                        'type' => '',
                        'producing_area' => '',
                        'budget' => $totalPrice,
                        'funds_type' => '',
                        'budget_item_name' => '',
                        'detail' => '',
                        'catalogue' => '',
                        'buymode' => '',
                        'proxycompany' => '',
                        'projecterName' => '',
                        'note' => ''
                    );
                    $o = 0;
//                    $worksheet->getRowDimension($num)->setRowHeight(25);
                    foreach ($value as $k => $v) {
                        $str = chr($ch + $o) . ($num);
                        $worksheet->getStyle($str)->applyFromArray($styleArray);
                        $worksheet->getStyle($str)->getFont()->setName('Arial')->setSize(11);
                        $worksheet->getCell($str)->setValue($v);
                        $o += 1;
                    }
                }

                //excel写入最后数据的小计
                if ($totalNum == ($va + 1) && $numRow > 1) {
                    self::setCommonCloumn($worksheet, $num, $totalPrice, $ch, $styleArray);
                }

                //重置小计数据
                if ($data1[$va]['companyname'] != $data1[$si]['companyname']) {
                    $numRow = 1;
                    $totalPrice = 0;
                }

                //重置合并表格值
                if ($data1[$va]['name'] != $data1[$si]['name']) {
                    $rowss = '';
                }
            }
        }
        $this->removeSheet($spreadsheet);
        // 结束进行导出
        ob_end_clean();
        ob_start();
        if (empty($filename)) {
            $filename = md5(time()) . ".xlsx";
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $filename);
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
    }

    /**
     * Notes: 招标合并单元格
     * @Auther: lv
     * @Email: 578530370@qq.com
     * @Date: 2020/4/21 17:00
     * @param $data
     * @param string $path
     * @return bool
     */
    function ExcelsMergeCells($data, $path = '', $dataTmp = array())
    {
        if (empty($data) || empty($path)) return false;
        $path = './officeTemplate/' . $path;
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->getDefaultRowDimension()->setRowHeight(27);
        //写入模板数据
        if (!empty($dataTmp)) {
            foreach ($dataTmp as $key => $value) {
                $worksheet->setCellValue($key, $value);
            }
        }

        //$worksheet->getActiveSheet()->setCellValue("H" . $pos, number_format(abs($v['value']),2,".",""));
        $worksheet->getStyle ('H')->getNumberFormat()->setFormatCode ("0.00");
        $worksheet->getStyle ('I')->getNumberFormat()->setFormatCode ("0.00");
        $worksheet->getStyle ('J')->getNumberFormat()->setFormatCode ("0.00");
        $worksheet->getStyle ('K')->getNumberFormat()->setFormatCode ("0.00");
        $worksheet->getStyle ('L')->getNumberFormat()->setFormatCode ("0.00");

        //计算excel行与列
        $rows = 1;
        foreach ($worksheet->getRowIterator(2) as $row) {
            $rows += 1;
        }
        //设置表格样式
        $styleArray = [
            //设置居中方式
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, //水平居中
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, //垂直居中
            ],
            //设置边框
            'borders' => [
                'outline' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\style\Border::BORDER_THIN, //细边
                    'color' => ['argb' => '00000000'], //黑色
                ],
            ],
        ];

        $ch = 65;
        $num = $rows;

        $numRow = 0;
        $totalPrice = 0;
        $totalNum = count($data);
        $rowss = '';
        $budgetTotal = 0;

        //序号
        $no = 0;
        $mergeids = '';
        for ($va = 0; $va < $totalNum; $va++) {
            $budgetTotal += $data[$va]['budget'];
            $num += 1;
            //设置行高
//            $worksheet->getDefaultRowDimension($num)->setRowHeight(25);
            $i = 0;

            $si = $va + 1;
            if ($si >= $totalNum) $si = $va - 1;

            //公司名称相同+1
            if ($data[$va]['companyname'] == $data[$si]['companyname']) {
                $numRow += 1;
            }

            //设置序号
            $mergeid = $data[$va]['mergeids'];
            if($mergeids != $mergeid && !isempt($mergeid)) {
                $no++;
                $mergeids = $mergeid;
                $data[$va]['id'] = $no;
            } else if(isempt($mergeid)){
                if(isempt($data[$va]['no'])) {
                    $no++;
                    $data[$va]['id'] = $no;
                }else{
                    $data[$va]['id'] = $no;
                }
            }
            unset($data[$va]['no']);

            //判断mergepeojectids是否有值
            if (!empty($data[$va]['mergeids']) && $data[$va]['mergeids'] == $data[$si]['mergeids']) $rowss .= $num . ',';
//            unset($data[$va]['mergeids']);
            $totalPrice += $data[$va]['budget'];
            //写入列表数据
            foreach ($data[$va] as $k => $v) {
                $str = chr($ch + $i) . ($num);
                $worksheet->getStyle($str)->applyFromArray($styleArray);
                $worksheet->getStyle($str)->getFont()->setName('Arial')->setSize(11);
                $worksheet->getStyle($str)->getAlignment()->setWrapText(true);
                $worksheet->getCell($str)->setValue($v);
                $i += 1;
            }

            //设置合并单元格
            if($si > $va) {
                if (!empty($data[$va]['mergeids']) && $data[$va]['mergeids'] != $data[$si]['mergeids'] && !empty($rowss)) {
                    $column = explode(',', $rowss);
                    $column1 = $column[0];
                    $worksheet->mergeCells("A$column1:A$num");
                    $worksheet->mergeCells("B$column1:B$num");
                    $worksheet->mergeCells("C$column1:C$num");
                    $worksheet->mergeCells("F$column1:F$num");
                    $worksheet->mergeCells("G$column1:G$num");
                    $worksheet->mergeCells("Y$column1:Y$num");
                }
            } else {
                if (!empty($data[$va]['mergeids']) && $data[$va]['mergeids'] == $data[$si]['mergeids'] && !empty($rowss)) {
                    $column = explode(',', $rowss);
                    $column1 = $column[0];
                    $worksheet->mergeCells("A$column1:A$num");
                    $worksheet->mergeCells("B$column1:B$num");
                    $worksheet->mergeCells("C$column1:C$num");
                    $worksheet->mergeCells("F$column1:F$num");
                    $worksheet->mergeCells("G$column1:G$num");
                    $worksheet->mergeCells("Y$column1:Y$num");
                }
            }



            //excel写入小计
            if (($data[$va]['companyname'] != $data[$si]['companyname'] && $numRow > 0) || ($va > $si && $data[$va]['companyname'] == $data[$si]['companyname'] && $numRow > 0)) {
                $num = $num+1;
                $value = array(
                    'id' => '小计',
                    'companyname' => '',
                    'name' => '',
                    'projecticp' => '',
                    'proicptime' => '',
                    'type' => '',
                    'buymode' => '',
                    'budget' => $totalPrice,
                    'aftercheckmoney' => '',
                    'zbmoney' => '',
                    'savemoney_ys' => '',
                    'savemoney_sj' => '',
                    'saverate_ys' => '',
                    'saverate_sj' => '',
                    'proxygov' => '',
                    'signupcompany' => '',
                    'proclamationdate' => '',
                    'startbiddate' => '',
                    'wbtime' => '',
                    'zbcompany' => '',
                    'issignagreement' => '',
                    'projectfiles' => '',
                    'projectprogress' => '',
                    'gathernote' => '',
                    'projecterName' => '',
                );
                $o = 0;
                $worksheet->getRowDimension($num)->setRowHeight(27);
                foreach ($value as $k => $v) {
                    $str = chr($ch + $o) . ($num);
                    $worksheet->getStyle($str)->applyFromArray($styleArray);
                    $worksheet->getStyle($str)->getFont()->setName('Arial')->setSize(11);
                    $worksheet->getCell($str)->setValue($v);
                    $o += 1;
                }
            }

            //excel写入最后数据的小计
//            if ($totalNum == ($va + 1) && $numRow > 0) {
//
//            }

            //重置小计数据
            if ($data[$va]['companyname'] != $data[$si]['companyname']) {
                $numRow = 1;
                $totalPrice = 0;
            }

            //重置合并表格值
            if ($data[$va]['mergeids'] != $data[$si]['mergeids']) {
                $rowss = '';
            }

            //删除多余单元格
            $worksheet->removeColumn('Z');
        }

        //excel写入最后数据的总计
        $value = array(
            'id' => '总计',
            'companyname' => '',
            'name' => '',
            'projecticp' => '',
            'proicptime' => '',
            'type' => '',
            'buymode' => '',
            'budget' => $budgetTotal,
            'aftercheckmoney' => '',
            'zbmoney' => '',
            'savemoney_ys' => '',
            'savemoney_sj' => '',
            'saverate_ys' => '',
            'saverate_sj' => '',
            'proxygov' => '',
            'signupcompany' => '',
            'proclamationdate' => '',
            'startbiddate' => '',
            'wbtime' => '',
            'zbcompany' => '',
            'issignagreement' => '',
            'projectfiles' => '',
            'projectprogress' => '',
            'gathernote' => '',
            'projecterName' => '',
        );
        $o = 0;
        $worksheet->getRowDimension($num+1)->setRowHeight(27);
        foreach ($value as $k => $v) {
            $str = chr($ch + $o) . ($num+1);
            $worksheet->getStyle($str)->applyFromArray($styleArray);
            $worksheet->getStyle($str)->getFont()->setName('Arial')->setSize(11);
            $worksheet->getCell($str)->setValue($v);
            $o += 1;
        }

        // 结束进行导出
        ob_end_clean();
        ob_start();
        if (empty($filename)) {
            $filename = md5(time()) . ".xlsx";
        }
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $filename);
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
    }

    /**
     * excel 公用方法
     * @param $worksheet
     * @param $data
     * @Auther: lv
     * @Email: 578530370@qq.com
     * @Date: 2020/3/30 14:21
     */
    private function commonExcel($worksheet, $data, $totalColumn = array())
    {
        //计算excel行与列
        $rows = 1;
        foreach ($worksheet->getRowIterator(2) as $row) {
            $rows += 1;
//            $column = 0;
//            foreach ($row->getCellIterator() as $cell) {
//                $column += 1;
//            }
        }
        //设置表格样式
        $styleArray = [
            //设置居中方式
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, //水平居中
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, //垂直居中
            ],
            //设置边框
            'borders' => [
                'outline' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\style\Border::BORDER_THIN, //细边
                    'color' => ['argb' => '00000000'], //黑色
                ],
            ],
        ];

        //写入数据
        $ch = 65;
        $num = $rows;
        foreach ($data as $key => $value) {
            $num += 1;
//            $worksheet->getRowDimension($num)->setRowHeight(25);
            $i = 0;
            foreach ($value as $k => $v) {
                $str = chr($ch + $i) . ($num);
                $worksheet->getStyle($str)->applyFromArray($styleArray);
                $worksheet->getStyle($str)->getFont()->setName('Arial')->setSize(11);
                $worksheet->getStyle($str)->getAlignment()->setWrapText(true);
                $worksheet->getCell($str)->setValue($v);
                $i += 1;
            }
            if ($totalColumn) {
                $str = chr($ch + $i) . ($num);
                $worksheet->getStyle($str)->applyFromArray($styleArray);
                $worksheet->getStyle($str)->getFont()->setName('Arial')->setSize(11);
                $worksheet->getStyle($str)->getAlignment()->setWrapText(true);
                $first = $totalColumn['first'] . $num;
                $second = $totalColumn['second'] . $num;
                $worksheet->setCellValue($str, "=SUM($first:$second)");
            }
        }
    }

    /**
     * 移除工作表
     * @param $spreadsheet
     * @Auther: lv
     * @Email: 578530370@qq.com
     * @Date: 2020/3/30 14:09
     */
    private function removeSheet($spreadsheet)
    {
        $sheetIndex1 = $spreadsheet->getIndex(
            $spreadsheet->getSheetByName('Sheet1')
        );
        $spreadsheet->removeSheetByIndex($sheetIndex1);
        $sheetIndex2 = $spreadsheet->getIndex(
            $spreadsheet->getSheetByName('Sheet2')
        );
        $spreadsheet->removeSheetByIndex($sheetIndex2);
        $sheetIndex3 = $spreadsheet->getIndex(
            $spreadsheet->getSheetByName('Sheet3')
        );
        $spreadsheet->removeSheetByIndex($sheetIndex3);
    }

    private function setCommonCloumn($worksheet, $num, $totalPrice, $ch, $styleArray)
    {
        $num = $num+1;
        $value = array(
            'id' => '小计',
            'companyname' => '',
            'name' => '',
            'type' => '',
            'producing_area' => '',
            'budget' => $totalPrice,
            'funds_type' => '',
            'budget_item_name' => '',
            'detail' => '',
            'catalogue' => '',
            'buymode' => '',
            'proxycompany' => '',
            'projecterName' => '',
            'note' => ''
        );
        $o = 0;
//        $worksheet->getRowDimension($num)->setRowHeight(25);
        foreach ($value as $k => $v) {
            $str = chr($ch + $o) . ($num);
            $worksheet->getStyle($str)->applyFromArray($styleArray);
            $worksheet->getStyle($str)->getFont()->setName('Arial')->setSize(11);
            $worksheet->getStyle($str)->getAlignment()->setWrapText(true);
            $worksheet->getCell($str)->setValue($v);
            $o += 1;
        }
    }

    /**
     * @param string $uid 必填 操作人id
     * @param string $table 必填 当前表名 eg：'cg_jieguo_list'
     * @param string $mid 必填 项目id
     * @param array $logs 选填 签章记录
     * @param string $a 必填 方法名
     * @param string $direction 选填 pdf版式（landscape 横板）
     * @return bool
     */
    function signatureWord($uid, $table, $mid, $logs = array() ,$a, $direction = '', $docType = 1)
    {
        if(empty($a)) return '参数不能为空';
        isset($data['doc_type']) && $docType = $data['doc_type'];
        $info = m($table)->getone('id='.$mid, 'status');
        $docInfo = m('zbcg_documents')->getone('mtype=\''.$table.'\' and mid='.$mid. ' and `doc_type`='.$docType, 'id,doc_name,doc_path,doc_type,status');

        $pdfPath = UPDIR . '/' . 'document' . '/' . date('Y-m') . '/';
        @mkdir($pdfPath, 0755, true);
        $time = md5(time());
        $pdfName = $time . ".pdf";
        $url = URL.'api.php?m=openpdf&a='.$a.'&id='.$mid;
//        $exce = 'wkhtmltopdf --load-error-handling ignore'." \"". $url ."\""." \"./" .$pdfPath.$pdfName. "\" >> E:\webRoot\oa\log_file.txt 2>&1 &";
        if(empty($docInfo)) {//第一次生成文档
            $pdf = new mikehaertl\wkhtmlto\Pdf();
            if(!empty($direction)) {
                $pdf->setOptions(array(
                    'orientation' => 'landscape'
                ));
            }
            $pdf->addPage($url);

            if (!$pdf->saveAs($pdfPath.$pdfName)) {
                echo $pdf->getError();
            }

            if(file_exists($pdfPath.$pdfName)){
                $param = array(
                    'doc_name' => $pdfName,
                    'doc_path' => $pdfPath.$pdfName,
                    'doc_type' => $docType,
                    'doc_suffix' => substr(strrchr($pdfName, '.'), 1),
                    'mtype' => $table,//接受参数文档所属模块
                    'mid' => $mid,//接受参数项目id
                    'optid' => $uid,
                    'status' => $info['status'] == 1 ? 1 : 0,
                );
                $docId = m('documents')->add($param);
                $this->commonLogs($logs, $docId, $pdfName, $uid, $pdfPath);
            }

        }elseif (($info['status'] == 0 && $docInfo['status'] == 0) || ($info['status'] == 1 && $docInfo['status'] == 0)) {
            $pdf = new mikehaertl\wkhtmlto\Pdf($url);
            if (!$pdf->saveAs($pdfPath.$pdfName)) {
                echo $pdf->getError();
            }

            if(file_exists($pdfPath.$pdfName)){
                $param = array(
                    'doc_name' => $pdfName,
                    'doc_path' => trim($pdfPath),
                    'doc_type' => $docType,
                    'doc_suffix' => substr(strrchr($pdfName, '.'), 1),
                    'optid' => $uid,
                    'status' => $info['status'] == 1 ? 1 : 0,
                );
                $docId = m('documents')->update($param, 'id='.$docInfo['id']);
                $this->commonLogs($logs, $docId, $pdfName, $uid, $pdfPath);
            }
        }else{
            m('documentslog')->add($uid, $docInfo['id']);
            m('documents')->download(trim($docInfo['doc_path'], $docInfo['doc_name']), $docInfo['doc_name']);
        }
    }

    private function wordToPdf($wordPath, $pdfPath, $filename)
    {
        if(PHP_OS == 'Linux'){
            $command = 'export HOME=/tmp/ && libreoffice6.3 --headless --invisible --convert-to pdf:writer_pdf_Export '.$wordPath.' --outdir '.$pdfPath;
        }else{
            $command = 'cmd /c soffice --headless --invisible --convert-to pdf:writer_pdf_Export '.$wordPath.' --outdir '.$pdfPath;
        }
        @exec($command);
        return $pdfPath.$filename;
    }

    private function commonLogs($logs, $docId, $pdfName, $uid, $pdfPath) {
        if(!empty($logs)){
            foreach ($logs as $log){
                foreach ($log['type'] as $type){
                    m('signaturelog')->add($type.'_' . $log['uid'], $log['uid'], $docId, $pdfName);
                }
            }
        }
        m('documentslog')->add($uid, $docId);
        m('documents')->download($pdfPath, $pdfName);
    }

    public function setSign($path, $poi, $signPath, $orientation = 'P', $unit= '', $widthHeight=array())
    {
        return c('AFPDF')->daorupdfifpdf($path,$poi,$signPath,$orientation,$unit,$widthHeight);
    }
}